package com.sihai.core.support;

import java.io.Serializable;
import java.sql.Timestamp;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.sihai.core.EntityMetaInfo;
import com.sihai.core.utils.UserContext;

public class EntityPersistInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 143172653961817994L;

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		if (!EntityMetaInfo.class.isInstance(entity)) {
			return super.onSave(entity, id, state, propertyNames, types);
		}

		for (int i = 0; i < propertyNames.length; i++) {
			if (EntityMetaInfo.MODIFYINFO_PROPERTY_NAME.creator_id.equals(propertyNames[i])) {
				Object creator_id = UserContext.getOperatorId();
				if (creator_id != null) {
					state[i] = creator_id;
				}
				continue;
			}

			if (EntityMetaInfo.MODIFYINFO_PROPERTY_NAME.create_date.equals(propertyNames[i])) {
				state[i] = new Timestamp(System.currentTimeMillis());
				continue;
			}
		}
		return true;
	}

	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (!EntityMetaInfo.class.isInstance(entity)) {
			return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
		}

		for (int i = 0; i < propertyNames.length; i++) {
			if (EntityMetaInfo.MODIFYINFO_PROPERTY_NAME.modifier_id.equals(propertyNames[i])) {
				Object modifier_id = UserContext.getOperatorId();
				if (currentState != null && modifier_id != null) {
					currentState[i] = modifier_id;
				}
				continue;
			}

			if (currentState != null && 
					EntityMetaInfo.MODIFYINFO_PROPERTY_NAME.modify_date.equals(propertyNames[i])) {
				currentState[i] = new Timestamp(System.currentTimeMillis());
				continue;
			}
		}
		return true;
	}

}
